package com.cmwa.solution.business.archiveManagement.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.solution.base.controller.BaseController;
import com.cmwa.solution.base.entity.Page;
import com.cmwa.solution.base.entity.Result;
import com.cmwa.solution.base.entity.SearchParam;
import com.cmwa.solution.business.archiveManagement.service.ArchiveManagementService;
import com.cmwa.solution.exception.ValidateFailedException;
import com.cmwa.solution.sys.attach.entity.AttachVo;
import com.cmwa.solution.sys.attach.service.AttachService;
import com.cmwa.solution.sys.dictionary.entity.DictionaryVo;
import com.cmwa.solution.sys.dictionary.service.DictionaryService;
import com.cmwa.solution.sys.msg.util.StringUtil;
import com.cmwa.solution.utils.cached.DictionaryCached;

import net.sf.json.JSONArray;

/**
 * 档案管理控制器
 * 
 * @author ex-chenxh
 * @date 2019-01-22 10:30:12
 */
@Controller
@RequestMapping("/business/archiveManagement")
public class ArchiveManagementController extends BaseController {
	
	private static final Log log = LogFactory.getLog(ArchiveManagementController.class);

	private final static String JSP_PATH = "business/archiveManagement/";
	@Resource
	private ArchiveManagementService archiveManagementService;
	@Resource
	private AttachService attachService;
	@Resource
	private DictionaryService dictionaryService;
	
		
	/**
	 * 跳转到列表页面
	 * @author ex-chenxh
	 * @date 2019-01-22 10:30:12
	 * @param model
	 * @return
	 */
	@RequestMapping("/archiveManagementListView")
	public String archiveManagementListView(ModelMap model) {
		log.info("前往档案管理列表页面");
		return JSP_PATH + "archiveManagementList";
	}
	
	/**
	 * 通过条件查询数据并分页
	 * @param param
	 * @return
	 */
	@RequestMapping("/archiveManagementListPage")
	@ResponseBody
	public Page<AttachVo> archiveManagementListPage(SearchParam param) {
		log.info("档案管理列表页面加载分页数据");
		return attachService.attAndRelAndExtListPage(param);
	}
	/**
	 * 前往档案新增页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/archiveAddView")
	public String archiveAddView(String actionType,String id,ModelMap model) throws ValidateFailedException {
		log.info("前往档案编辑页面，当前操作类型为：" + actionType);
		AttachVo attachVo = null;
		List<DictionaryVo> dictionaryList = null;
		String attach2Json = "";
		String archiveType2Json = "";
		
		//执行动作不为空 并且 不等于add类型的情况，需要根据ID加载档案信息
		if(StringUtils.isNotBlank(actionType) && !"add".equals(actionType)) {
			//加载档案管理信息，由于列表展示数据的维度是附件，所以展示详情数据只需展示1条与附件信息关联的数据
			attachVo = archiveManagementService.getArchiveManagementById(id);
			//如果档案信息不为空，则加载附件信息
			if(null != attachVo) {
				/*//用于验证多个附件显示添加拓展字段是否正确，档案管理功能忽略
			    List<AttachVo> attachVoList = attachService.attAndRelAndExtList(new SearchParam());
			    attach2Json = StringUtil.changeSpecialCharacter(JSONArray.fromObject(attachVoList).toString());*/
				attach2Json = StringUtil.changeSpecialCharacter(JSONArray.fromObject(attachVo).toString());
			}else {
				log.error("根据前端传递过来的主键：" + id + ",没有获取到相关数据");
				throw new ValidateFailedException("根据前端传递过来的信息,没有获取到相关数据");
			}
		}
		//加载拓展字段下拉选项
		dictionaryList = DictionaryCached.getDictionaryByType("ARCHIVE_TYPE");
		//如果拓展字段下拉选项信息不为空，则将拓展字段下拉选项信息转成JSON格式
		if(null != dictionaryList){
			archiveType2Json = StringUtil.changeSpecialCharacter(JSONArray.fromObject(dictionaryList).toString());
		}
		//设置前端要显示的数据
		model.addAttribute("attach", attachVo);
		model.addAttribute("actionType", actionType);
		model.addAttribute("attachList", attach2Json);
		model.addAttribute("expandList", archiveType2Json);
		
		return JSP_PATH + "archiveManagementAdd";
	}
	
	/**
	 * 新增档案信息
	 * @param archiveVo
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveArchive",method = {RequestMethod.POST})
	public String saveArchive(@RequestBody List<Map<String,String>> archiveList,ModelMap model) throws ValidateFailedException {
		log.info("新增档案信息" );
		//前台传递过来的集合不能为空
		if (CollectionUtils.isNotEmpty(archiveList)) {
			log.info("新增关联附件数：" + archiveList.size());
			//将业务和附件的关联关系存入数据库中
			archiveManagementService.insertArchiveManagement(archiveList);
			return redirectSuccess();
		}else {
			log.error("新增失败，参数archiveList不能为空:"+archiveList);
			model.addAttribute("exception", "新增失败，参数不能为空");
			return redirectExecFaild();
		}
	}
	/**
	 * 修改档案信息
	 * @param archiveVo
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/updateArchive",method = {RequestMethod.POST})
	public String updateArchive(@RequestBody List<Map<String,String>> archiveList,ModelMap model) throws Exception {
		log.info("修改档案信息" );
		//前台传递过来的集合不能为空
		if (CollectionUtils.isNotEmpty(archiveList)) {
			log.info("修改关联附件数：" + archiveList.size());
			//将业务和附件的关联关系存入数据库中
			archiveManagementService.updateArchiveManagement(archiveList);
			return redirectSuccess();
		}else {
			log.error("修改失败，参数不能为空");
			model.addAttribute("exception", "修改失败，参数不能为空");
			return redirectExecFaild();
		}
	}
	/**
	 * 删除档案信息
	 * @param archiveVo
	 * @param model
	 * @return
	 * @throws ValidateFailedException
	 */
	@RequestMapping("/deleteArchive")
	@ResponseBody
	public Result<Object> deleteArchive(@RequestParam("id") String id,ModelMap model) throws ValidateFailedException {
		log.info("根据主键删除档案信息，id：" + id );
		
		Result<Object> result = new Result<Object>();
		boolean isComplete = false;
		//判断需要删除的主键是否为空
		if(StringUtils.isNotBlank(id)) {
			int status = archiveManagementService.deleteArchiveManagement(id);
			log.info("根据主键删除相关记录数：" + status);
			if(status > 0) {
				isComplete = true;
			}
		}else {
			log.error("需要删除的id不能为空！");
			result.setMessage("需要删除的主键不能为空！");
		}
		result.setSuccess(isComplete);
		return result;
	}
	/**
	 * 批量下载档案管理附件
	 * @param attIds
	 * @param response
	 * @throws ValidateFailedException
	 */
	@RequestMapping("/batchDownAttach")
	public void batchDownAttach(@RequestParam("attIds") String attIds,HttpServletRequest request,HttpServletResponse response) throws ValidateFailedException {
		log.info("批量下载档案管理附件,attIds:" + attIds);
		//判断前端传递过来的附件主键集合是否为空
		if(StringUtils.isNotBlank(attIds)) {
			attachService.downloadAttachZip(attIds, "档案管理", request, response);
		}else {
			log.error("批量下载档案管理附件，attIds不能为空");
			throw new ValidateFailedException("批量下载档案管理附件，请至少选择一条记录进行下载");
		}
	}
	
}
